package com.ck.shardingspheremaster.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.HashSet;

/**
 * @Author yd
 * @Date 2019/1/3 21:10
 */
@Slf4j
public class MyShardingConfig2 implements RangeShardingAlgorithm {

    /**
     * lower 为 between and 中的较小值
     * upper 为 between and 中的较大值
     * 如果lower小于等于5，tables集合中就要加入t_user0表
     * 如果lower大于5，tables集合中就要加入t_user1表
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection availableTargetNames, RangeShardingValue shardingValue) {

        Collection<String> tables = new HashSet<>();
        if(availableTargetNames.contains("t_user")){
            if(shardingValue.getColumnName().equalsIgnoreCase("sex")){
                Comparable lower = shardingValue.getValueRange().lowerEndpoint();
                Comparable upper = shardingValue.getValueRange().upperEndpoint();

                int lowerResult = lower.compareTo(5);
                int upperResult = upper.compareTo(5);

                if(lowerResult<=0){
                    tables.add("t_user_0".toUpperCase());
                    if(upperResult>0){
                        tables.add("t_user_2".toUpperCase());
                    }
                }else{
                    tables.add("t_user_2".toUpperCase());
                }
            }
        }
        log.info("范围分片算法 [doSharding]:===============================> {}",tables);
        return tables;
    }



}
